/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package	dao;

import Hibernate.HibernateUtil;
import pojo.Author;
import pojo.Book;
import pojo.Status;
import pojo.User;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class UserDAO extends AbstractDAO {

	@Override
	protected Class getPOJOClass() {
		// TODO Auto-generated method stub
		return User.class;
	}
	
    public User getUserByID(int id){
        User author = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            author = (User)session.get(Author.class, id);
        }
        catch(HibernateException ex){
            
        }
        finally{
            session.close();
        }
        return author;
    }
    
    public int kiemTraDangNhap(String id, String pass)
    {
    	int kq=-1;
    	UserDAO ud= new UserDAO();
    	User t=this.getUser(id);
    	if(t==null) return kq;
    	else
    	{
    		if(pass.equals(t.getPassword()))
    			return 1;
    		else return 0;
    	}
    }
   
    public User getUser(String id)
    {
		User kh = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			kh = (User) session.get(User.class, id);
		} catch (HibernateException e) {
			System.err.println(e);
		} finally {
			session.close();
		}
		return kh;
    }

	public boolean kiemTraDaTonTaiTenDangNhap(String tenDangNhap) {
		List<User> ds = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			String sql = "select kh from User kh where kh.userId=:n";
			Query query = (Query) session.createQuery(sql).setParameter("n",tenDangNhap);
			ds = query.list();
		} catch (HibernateException ex) {
			System.out.println(ex);
		} finally {
			session.close();
		}
		if (ds.size() > 0)
			return true;
		else
			return false;

	}
	
	public Boolean kiemTraDaTonTaiEmail(String _email) {
		List<User> ds = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			String sql = "select kh from User kh where kh.email=:n";
			Query query = (Query) session.createQuery(sql).setParameter("n",_email);
			ds = query.list();
		} catch (HibernateException ex) {
			System.out.println(ex);
		} finally {
			session.close();
		}
		if (ds.size() > 0)
			return true;
		else
			return false;
	}

	public String getYear(Date d) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy");
		return (dateFormat.format(d));
	}
	
	public Boolean insertUser(String hoTen, String ngay, String thang,
			String nam, String diaChi, String email, String dienThoai,
			String tenDangNhap, String matKhau) {
		Boolean insert = false;
		UserDAO khDAO = new UserDAO();
		if (khDAO.kiemTraDaTonTaiTenDangNhap(tenDangNhap))
			return insert;
		String NgayThangNam = thang + "/" + ngay + "/" + nam;
		SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");
		Date _ngayThangNam = null;
		try {
			_ngayThangNam = dateFormat.parse(NgayThangNam);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int currentYear = Integer.parseInt(getYear(new Date()));
		int _tuoi = currentYear - Integer.parseInt(getYear(_ngayThangNam));
		StatusDAO stdao= new StatusDAO();
		Status st = stdao.getStatusByID(4);
		User kh = new User(tenDangNhap,st, hoTen, _ngayThangNam,
				 matKhau, email, dienThoai,1,diaChi,null,null);
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.save(kh);
			session.flush();
			transaction.commit();
			insert = true;
		} catch (HibernateException ex) {
			// Log the exception
			transaction.rollback();
			System.err.println(ex);
		} finally {
			session.close();
		}
		return insert;

	}

	public Boolean capNhatThongTinUser(User us) {
		UserDAO khDAO = new UserDAO();
		Session session = HibernateUtil.getSessionFactory().openSession();
		if (khDAO.getUser(us.getUserId())==null) {
				return false;
		}
		Transaction transaction = null;
		try {
				transaction = session.beginTransaction();
				session.update(us);
				session.flush();
				transaction.commit();
		} catch (HibernateException ex) {
				// Log the exception
				transaction.rollback();
				System.err.println(ex);
		} finally {
				session.close();
		}
		return true;
		
	}
	
	public String layMatKhauQuaEmail(String _email) {
		List<User> ds = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			String sql = "select kh from User kh where email=:n";
					
			Query query = (Query) session.createQuery(sql).setParameter("n",_email);
			ds = query.list();
		} catch (HibernateException ex) {
			System.out.println(ex);
		} finally {
			session.close();
		}
		if (ds.size() > 0)
		{
			return ds.get(0).getPassword();
		}
		else
			return null;
	}
	
	public boolean capNhatMatKhau(User user,String mkcu, String mkmoi, String xn)
	{
		boolean flag=false;
		User us=this.getUser(user.getUserId());
		if(us.getPassword().equals(mkcu))
		{
			us.setPassword(mkmoi);
			capNhatThongTinUser(us);
			flag=true;
		}
		return flag;
	}

	public Boolean themUser(String _hoVaTen, String _ngay, String _thang,
			String _nam, String _diaChi, String _email, String _dienThoai,
			String _tenDangNhap, String _matKhau)
			throws ParseException {
		Boolean insert = false;
		UserDAO khDAO = new UserDAO();
		if (khDAO.kiemTraDaTonTaiTenDangNhap(_tenDangNhap))
			return insert;
		String NgayThangNam = _thang + "/" + _ngay + "/" + _nam;
		SimpleDateFormat dateFormat = new SimpleDateFormat("mm/dd/yyyy");
		Date _ngayThangNam = dateFormat.parse(NgayThangNam);
		int currentYear = Integer.parseInt(getYear(new Date()));
		int _tuoi = currentYear - Integer.parseInt(getYear(_ngayThangNam));
		StatusDAO stdao= new StatusDAO();
		Status st = stdao.getStatusByID(4);
		User kh = new User(_tenDangNhap,st, _hoVaTen, _ngayThangNam, _matKhau, _email, _dienThoai,0,_diaChi,null,null);
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.save(kh);
			session.flush();
			transaction.commit();
			insert = true;
		} catch (HibernateException ex) {
			// Log the exception
			transaction.rollback();
			System.err.println(ex);
		} finally {
			session.close();
		}
		return insert;
	}
	
	public List<User> timKiemUser(String tendangnhap,String hoten, String diachi,int trang, int sosanphamtrentrang, int kieuSort)
	{
		List<User> ds ;
		Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "select s from User s where 1=1 and s.isAdmin = 0 ";
		if(!tendangnhap.trim().equals(""))
			hql += " and s.userId like '%" + tendangnhap.trim()+"%'";
		if(!hoten.trim().equals(""))
			hql += " and s.name like '%" + hoten.trim()+"%'";
		if(!diachi.trim().equals(""))
			hql += " and s.address like '%" + diachi.trim()+"%'";
		switch(kieuSort)
		{
			case 1:
				hql+=" order by s.userId asc";
				break;
			case 2:
				hql+=" order by s.userId desc";
				break;
			case 3:
				hql+=" order by s.name asc";
				break;
			case 4:
				hql+=" order by s.name desc";
				break;						
		}
		Query query = session.createQuery(hql);
	    query.setFirstResult((trang - 1) * sosanphamtrentrang);
		query.setMaxResults(sosanphamtrentrang);
		ds = (List<User>) query.list();
		session.close();
		return ds;
	}
	
	public long tinhSoTrangTimKiem(String tendangnhap,String hoten, String diachi ,int soTKtrentrang)
	{
		long soTrang = 0;
		long soLuong = 0;
		List<User> ds ;
		Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "select  count(*)  from User s where 1=1 and s.isAdmin=0 ";
		if(!tendangnhap.trim().equals(""))
			hql += " and s.userId like '%" + tendangnhap.trim()+"%'";
		if(!hoten.trim().equals(""))
			hql += " and s.name like '%" + hoten.trim()+"%'";
		if(!diachi.trim().equals(""))
			hql += " and s.address like '%" + diachi.trim()+"%'";
		
		
		Query query = session.createQuery(hql);
		Object obj = query.uniqueResult();
		soLuong = (Long)obj;
		if(soTKtrentrang == -1)
			soTrang = 1;
		else{
			soTrang = soLuong / soTKtrentrang;
			if(soLuong % soTKtrentrang != 0)
				soTrang++;
		}
		session.close();
		return soTrang;
	}

	public long tinhKetQuaTimKiem(String tendangnhap,String hoten, String diachi ,int soTKtrentrang)
	{
		long soTrang = 0;
		long soLuong = 0;
		List<User> ds ;
		Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "select  count(*)  from User s where 1=1 and s.isAdmin=0 ";
		if(!tendangnhap.trim().equals(""))
			hql += " and s.userId like '%" + tendangnhap.trim()+"%'";
		if(!hoten.trim().equals(""))
			hql += " and s.name like '%" + hoten.trim()+"%'";
		if(!diachi.trim().equals(""))
			hql += " and s.address like '%" + diachi.trim()+"%'";
		
		
		Query query = session.createQuery(hql);
		Object obj = query.uniqueResult();
		soLuong = (Long)obj;
		return soLuong;
	}
	

	public Boolean delete(User us) {
		UserDAO khDAO = new UserDAO();
		Session session = HibernateUtil.getSessionFactory().openSession();
		if (khDAO.getUser(us.getUserId())==null) {
				return false;
		}
		boolean flag=false;
		Transaction transaction = null;
		try {
				transaction = session.beginTransaction();
				session.delete(us);
				session.flush();
				transaction.commit();
				flag=true;
		} catch (HibernateException ex) {
				// Log the exception
				transaction.rollback();
				System.err.println(ex);
		} finally {
				session.close();
		}
		
		return flag;
		
	}
}
